package com.blank.shop.ribbon.consumer;

import com.blank.shop.ribbon.ShopRibbonApplication;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.context.annotation.Profile;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpMethod;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

import javax.annotation.Resource;
import java.net.URI;
import java.util.List;

/**
 * <br/>Date 2021/8/31
 * <br/>Time 16:32:00
 *
 * @author _blank
 */
@Profile({ShopRibbonApplication.SERVER_CONSUMER})
@RestController
public class RibbonConsumerController {

    @Resource
    private RestTemplate restTemplate;

    @Resource
    private RestTemplate restTemplatePrimeval;

    @Resource
    private DiscoveryClient discoveryClient;

    @GetMapping(path = {"print-discovery-client"})
    public ResponseEntity<String> printDiscoveryClient() {
        final StringBuilder info = new StringBuilder();

        final List<String> services = this.discoveryClient.getServices();
        for (String service : services) {
            info.append(service).append(" : ");
            final List<ServiceInstance> instances = this.discoveryClient.getInstances(service);
            for (ServiceInstance instance : instances) {
                final URI uri = instance.getUri();
                final String s = uri.toString();
                info.append(" , ").append(s);
            }
            info.append("\n");
        }

        return ResponseEntity.ok(info.toString());
    }

    @GetMapping
    public ResponseEntity<String> sayHello() {
        // eureka、zookeeper、consul使用注册中心
        final String url = "http://" + ShopRibbonApplication.SERVER_PROVIDER_NAME + "/say-hello";
        return restTemplate.exchange(url, HttpMethod.POST, HttpEntity.EMPTY, String.class);
    }

    @GetMapping(path = {"say-hello-primeval"})
    public ResponseEntity<String> sayHelloPrimeval() {
        // 原始直接连接服务提供者
        final String url = "http://192.168.65.1:9218/say-hello";
        return restTemplatePrimeval.exchange(url, HttpMethod.POST, HttpEntity.EMPTY, String.class);
    }

}
